<template>
  <div>
    <div
      class="all"
      v-show="!dialogVisible"
    >
      <div class="search_box">
        <div>
          <div class="search_title">分类标题</div>
          <div>
            <el-input v-model="input" class="seek" placeholder="请输入标题" />
          </div>
        </div>
        <div class="search_right">
          <div class="search_title">创建时间</div>
          <div>
            <el-date-picker
              v-model="value1"
              type="daterange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              size="default"
              @change="debouncedSearch"
            />
          </div>
        </div>
      </div>
      <div class="line"></div>
      <div class="button_box">
        <el-button type="primary" class="butten" @click="adds()">新增</el-button>
        <el-button type="danger" class="butten" @click="deleteSelectedRows"
          >批量删除</el-button
        >
      </div>
      <div class="table_box">
        <el-table
          :data="filteredData"
          ref="multipleTableRef"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column label="序号" width="120" align="center">
            <template #default="scope">{{ scope.row.id }}</template>
          </el-table-column>
          <el-table-column label="标题" align="center">
            <template #default="scope">{{ scope.row.title }}</template>
          </el-table-column>

          <el-table-column property="updatetime" label="创建时间" align="center" />
          <el-table-column label="操作" align="center">
            <template #default="scope">
              <el-button type="primary" text @click="editRow(scope.row)">编辑</el-button>
              <el-button type="danger" text @click="deleteRow(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <div class="demo-pagination-block">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="total"
            @current-change="fetchData"
            @size-change="fetchData"
            layout="total, sizes, prev, pager, next, jumper"
            :page-sizes="[10, 20, 30, 40]"
          />
        </div>
      </div>
    </div>

    <!-- 添加遮罩层 -->
    <div v-show="dialogVisible" class="dialog-mask"></div>

    <div
      class="windows"
      v-show="dialogVisible"
    >
      <div class="windows_box">
        <div class="windows_title">{{ titles }}</div>
        <div class="line"></div>
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules">
          <div class="windows_content">
            <div class="content_left">
              <el-form-item label="分类名称" prop="title">
                <el-input
                  v-model="ruleForm.title"
                  class="inputs"
                  placeholder="请输入分类名称"
                />
              </el-form-item>
            </div>
          </div>
          <div class="windows_content_box">
            <el-form-item>
              <el-button type="primary" @click="submitForm(ruleFormRef)">
                确定
              </el-button>
              <el-button @click="resetForm(ruleFormRef)">取消</el-button>
            </el-form-item>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ElMessage, ElMessageBox } from "element-plus";
import { reactive, onMounted, ref, watch } from "vue";
import { goodsTypeList, goodsTypeAdd, goodsTypeDel } from "/@/api/score/score_goods_type/index";
import "/src/css/business.css";

// 图片上传

const data = ref<any[]>([]);// 列表数据
const originalData = ref<any[]>([]);// 原始数据
const filteredData = ref<any[]>([]);// 过滤后的数据
const value1 = ref(null);// 搜索框绑定值
const currentPage = ref(1);// 当前页
const pageSize = ref(10);// 每页显示条数
const total = ref(0);// 总条数
const dialogVisible = ref(false);// 弹窗显示
const multipleTableRef = ref();// 多选表格
const selectedRows = ref<any[]>([]);// 选中行
const ruleFormRef = ref();// 表单
const input = ref("");// 搜索框绑定值
const titles = ref("");// 标题
// 表单数据
const ruleForm = reactive({
  img: "",
  title: "",
  status: 1,
  id: "",
});
// 自定义验证函数：检查是否仅包含空格
const validateNoOnlyWhitespace = (rule: any, value: string, callback: Function) => {
  if (value.trim() === '') {
    callback(new Error(rule.message));
  } else {
    callback();
  }
};

// 表单验证
const rules = {
  title: [
    { required: true, message: "请输入分类名称", trigger: "blur" },
    { min: 2, max: 10, message: "长度在 2 到 10 个字符", trigger: "blur" },
    { validator: validateNoOnlyWhitespace, message: "不能只有空格", trigger: ["blur", "change"] }
  ],
};

const fileList = ref([]);
//获取数据
const fetchData = () => {
  goodsTypeList({ page: currentPage.value, pageSize: pageSize.value })
    .then((res) => {

      originalData.value = res.data.map((item: any) => ({
        ...item,
        showBoolean: item.status === 1,
      }));
      data.value = [...originalData.value];
      filteredData.value = [...originalData.value];
      total.value = res.data.length;
      filterData();
    })
    .catch(() => {
      ElMessage.error("获取数据失败，请稍后再试！");
    });
};

onMounted(() => {
  fetchData();
});
//分页
function filterData() {
  if (!data.value || !Array.isArray(data.value)) return;

  let filtered = data.value.filter((item: any) => {
    const nameMatch =
      !input.value ||
      item.title?.toLowerCase().trim().includes(input.value.toLowerCase().trim());
    return nameMatch;
  });

  filteredData.value = filtered;
  total.value = filtered.length;
  currentPage.value = 1; // 重置当前页码
}
// 使用防抖机制
let debounceTimer: NodeJS.Timeout | null = null;
const debouncedSearch = () => {
  if (debounceTimer) clearTimeout(debounceTimer);
  debounceTimer = setTimeout(search, 500);
};

// 处理表格选择变化
const handleSelectionChange = (val: any[]) => {
  selectedRows.value = val;
};
// 定义 search 函数，并确保拼写正确
const search = () => {
  if (!value1.value || !value1.value[0] || !value1.value[1]) {
    
    //清空后
    return;
  }

  const startTime = new Date(value1.value[0]).getTime();
  const endTime = new Date(value1.value[1]).getTime();

  filteredData.value = originalData.value.filter((item: any) => {
    const itemTime = new Date(item.updatetime).getTime();
    return itemTime >= startTime && itemTime <= endTime;
  });

  total.value = filteredData.value.length;
};
watch([input,value1], () => {
  filterData();
});

// 删除
const deleteRow = async (row: any) => {
  try {
    await ElMessageBox.confirm("确定要删除该条记录吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    await goodsTypeDel({ ids: row.id }); // 调用 API 删除数据
    ElMessage.success("删除成功！");
    fetchData();
    // 更新本地数据
    originalData.value = originalData.value.filter((item) => item.id !== row.id);
    filteredData.value = filteredData.value.filter((item) => item.id !== row.id);
    total.value--;

    // 重新应用搜索条件
  } catch (error) {
    ElMessage.error("删除失败，请稍后再试！");
  }
};
// 批量删除
const deleteSelectedRows = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请先选择要删除的记录");
    return;
  }

  try {
    await ElMessageBox.confirm("确定要删除选中的记录吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    const idsToDelete = selectedRows.value.map((row) => row.id);

    await goodsTypeDel({ ids: idsToDelete }); // 调用 API 批量删除数据

    ElMessage.success("删除成功！");

    // 更新本地数据
    originalData.value = originalData.value.filter(
      (item) => !idsToDelete.includes(item.id)
    );
    filteredData.value = filteredData.value.filter(
      (item) => !idsToDelete.includes(item.id)
    );
    total.value -= idsToDelete.length;

    // 清空选中状态
    selectedRows.value = [];
    multipleTableRef.value.clearSelection();
  } catch (error) {
    ElMessage.error("删除失败，请稍后再试！");
  }
};

// 新增逻辑
const adds = () => {
  titles.value = "新增";
  ruleForm.id = "";
  ruleForm.title = "";
  dialogVisible.value = true;
};

// 编辑逻辑
const editRow = (row: any) => {
  titles.value = "编辑";
  dialogVisible.value = true;
  // 填充表单数据
  Object.assign(ruleForm, row);
};

// 提交表单
const submitForm = async (formEl: any) => {
  if (!formEl) return;
  for(let i = 0; i < data.value.length; i++){
    if(data.value[i].title == ruleForm.title){
      ElMessage.warning("请勿重复添加！");
      return;
    }
  }
  await formEl.validate(async (valid: boolean) => {
    if (valid) {
      try {
        await goodsTypeAdd(ruleForm); // 调用 API 添加数据
        ElMessage.success("操作成功！");
        fetchData(); // 刷新数据
        dialogVisible.value = false;
      } catch (error) {
        ElMessage.error("添加失败，请稍后再试！");
      }
    } else {
      ElMessage.warning("请填写完整信息！");
    }
  });
};

// 重置表单
const resetForm = (formEl?: any) => {
  if (formEl) {
    formEl.resetFields();
  } else {
    ruleForm.img = "";
    fileList.value = [];
  }
  dialogVisible.value = false; // 关闭弹窗
};
</script>

<style scoped>

</style>